package com.zut.dao.impl;

import com.alibaba.druid.util.StringUtils;
import com.zut.dao.FoodDao;
import com.zut.pojo.Food;
import com.zut.utils.DruidUtil;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 张晨
 * @date 2024/9/19 22:28
 * @desc
 */
public class FoodDaoImpl implements FoodDao {
    private JdbcTemplate jdbcTemplate = new JdbcTemplate(DruidUtil.getDataSource());
    @Override
    public List<Food> selectByfoodNameAndStatus(Food food, Integer currentPage, Integer pageSize) {
        List list = new ArrayList();
        String sql = "select * from food where 1=1 ";
        if (!StringUtils.isEmpty(food.getFoodName())){
            sql += " and food_name like concat('%',?,'%')";
            list.add(food.getFoodName());
        }
        if (food.getStatus() !=null){
            sql += " and status = ?";
            list.add(food.getStatus());
        }
        sql += " limit "+(currentPage - 1)*pageSize + ","+pageSize;
        if (list.size() >0){
            return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Food.class),list.toArray());
        }else {
            return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Food.class));
        }
    }

    @Override
    public Long countByfoodNameAndStatus(Food food) {
        List list = new ArrayList();
        String sql = "select count(*) from food where 1=1 ";
        if (!StringUtils.isEmpty(food.getFoodName())){
            sql += " and food_name like concat('%',?,'%')";
            list.add(food.getFoodName());
        }
        if (food.getStatus() !=null){
            sql += " and status = ?";
            list.add(food.getStatus());
        }
        if (list.size() >0){
            return jdbcTemplate.queryForObject(sql,Long.class,list.toArray());
        }else {
            return jdbcTemplate.queryForObject(sql,Long.class);
        }
    }
}
